from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework_simplejwt.authentication import JWTAuthentication
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from django.core.exceptions import ObjectDoesNotExist

from .models import PromptTemplate
from .serializers import PromptTemplateSerializer
from apps.utils.response_utils import api_response, ResponseCode


class CreateTemplateView(APIView):
    """创建提示词模版"""

    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="创建提示词模版",
        request_body=PromptTemplateSerializer,
        responses={
            200: openapi.Response(description="创建成功"),
            400: openapi.Response(description="请求数据无效"),
        },
        tags=["模版管理"],
    )
    def post(self, request, *args, **kwargs):
        serializer = PromptTemplateSerializer(data=request.data)
        if serializer.is_valid():
            try:
                serializer.save()
                return api_response(
                    ResponseCode.SUCCESS, "模版创建成功", serializer.data
                )
            except Exception as e:
                return api_response(
                    ResponseCode.INTERNAL_SERVER_ERROR, f"创建失败: {str(e)}"
                )
        return api_response(
            ResponseCode.BAD_REQUEST, f"数据验证失败: {serializer.errors}"
        )


class UpdateTemplateView(APIView):
    """更新提示词模版"""

    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="更新提示词模版",
        request_body=PromptTemplateSerializer,
        responses={
            200: openapi.Response(description="更新成功"),
            400: openapi.Response(description="请求数据无效"),
            404: openapi.Response(description="模版不存在"),
        },
        tags=["模版管理"],
    )
    def put(self, request, template_id, *args, **kwargs):
        try:
            template = PromptTemplate.objects.get(id=template_id)
            serializer = PromptTemplateSerializer(
                template, data=request.data, partial=True
            )
            if serializer.is_valid():
                serializer.save()
                return api_response(
                    ResponseCode.SUCCESS, "模版更新成功", serializer.data
                )
            return api_response(
                ResponseCode.BAD_REQUEST, f"数据验证失败: {serializer.errors}"
            )
        except ObjectDoesNotExist:
            return api_response(ResponseCode.NOT_FOUND, "模版不存在")
        except Exception as e:
            return api_response(
                ResponseCode.INTERNAL_SERVER_ERROR, f"更新失败: {str(e)}"
            )


class DeleteTemplateView(APIView):
    """删除提示词模版"""

    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="删除提示词模版",
        responses={
            200: openapi.Response(description="删除成功"),
            404: openapi.Response(description="模版不存在"),
            500: openapi.Response(description="删除失败"),
        },
        tags=["模版管理"],
    )
    def delete(self, request, template_id, *args, **kwargs):
        try:
            template = PromptTemplate.objects.get(id=template_id)
            template.delete()
            return api_response(ResponseCode.SUCCESS, "模版删除成功")
        except ObjectDoesNotExist:
            return api_response(ResponseCode.NOT_FOUND, "模版不存在")
        except Exception as e:
            return api_response(
                ResponseCode.INTERNAL_SERVER_ERROR, f"删除失败: {str(e)}"
            )


class GetTemplateView(APIView):
    """获取提示词模版详情"""

    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="获取提示词模版详情",
        responses={
            200: PromptTemplateSerializer,
            404: openapi.Response(description="模版不存在"),
            500: openapi.Response(description="获取失败"),
        },
        tags=["模版管理"],
    )
    def get(self, request, template_id, *args, **kwargs):
        try:
            template = PromptTemplate.objects.get(id=template_id)
            serializer = PromptTemplateSerializer(template)
            return api_response(ResponseCode.SUCCESS, "获取成功", serializer.data)
        except ObjectDoesNotExist:
            return api_response(ResponseCode.NOT_FOUND, "模版不存在")
        except Exception as e:
            return api_response(
                ResponseCode.INTERNAL_SERVER_ERROR, f"获取失败: {str(e)}"
            )


class ListTemplateView(APIView):
    """获取提示词模版列表"""

    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="获取提示词模版列表",
        responses={
            200: openapi.Response(description="获取成功"),
            500: openapi.Response(description="获取失败")
        },
        tags=["模版管理"],
    )
    def get(self, request, *args, **kwargs):
        try:
            # 构建查询
            queryset = PromptTemplate.objects.all().order_by("-create_at")

            serializer = PromptTemplateSerializer(queryset, many=True)

            return api_response(ResponseCode.SUCCESS, "获取成功", serializer.data)
        except Exception as e:
            return api_response(
                ResponseCode.INTERNAL_SERVER_ERROR, f"获取失败: {str(e)}"
            )
